import abc
import sqlite3
import re
from typing import Any, Optional
from langchain.tools import BaseTool


class MyTimer(BaseTool, abc.ABC):
    name: str = "MyTimer"
    description: str = ("用于设置日程。接受3个参数，格式为: HH:MM|YYYYYYY|事项内容，所用标点符号必须为标准的英文字符。"
                        "'HH:MM' 表示时间（24小时制），'YYYYYYY' 表示循环规则（每位代表一天，从星期一至星期日，1为循环，0为不循环，"
                        "如'1000100'代表每周一和周五循环），'事项内容' 是提醒的具体内容。返回例子：15:15|0000000|提醒主人叫咖啡")

    uid: int = 0

    async def _arun(self, *args: Any, **kwargs: Any) -> Any:
        # 当前没有实现异步运行的方法
        pass

    def _run(self, para: str) -> str:
        parts = para.split("|")
        if len(parts) != 3:
            return self._format_error("输入格式错误，请按照 HH:MM|YYYYYYY|事项内容 格式提供参数")

        time, repeat_rule, content = [part.strip("'") for part in parts]

        if not self._is_valid_time(time):
            return self._format_error("时间格式错误。请按照'HH:MM'格式提供时间。")

        if not self._is_valid_repeat_rule(repeat_rule):
            return self._format_error("循环规则格式错误。请提供长度为7的0和1组成的字符串。")

        if not isinstance(content, str) or not content:
            return self._format_error("事项内容必须为非空字符串。")

        try:
            self._insert_into_db(time, repeat_rule, content)
        except Exception as e:
            return self._format_error(f"数据库错误: {e}")

        return "日程设置成功"

    @staticmethod
    def _is_valid_time(time_str: str) -> bool:
        return bool(re.match(r'^[0-2][0-9]:[0-5][0-9]$', time_str))

    @staticmethod
    def _is_valid_repeat_rule(rule_str: str) -> bool:
        return bool(re.match(r'^[01]{7}$', rule_str))

    @staticmethod
    def _format_error(message: str) -> str:
        return f"错误: {message}"

    def _insert_into_db(self, time: str, repeat_rule: str, content: str):
        with sqlite3.connect('timer.db') as conn:
            cursor = conn.cursor()
            cursor.execute("INSERT INTO timer (time, repeat_rule, content, uid) VALUES (?, ?, ?, ?)",
                           (time, repeat_rule, content, self.uid))
            conn.commit()


if __name__ == "__main__":
    my_timer = MyTimer()
    result = my_timer._run("15:15|0000001|提醒主人叫咖啡")
    print(result)